package com.atguigu.tingshu.search.config;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class ThreadPoolExecutorConfig {

    //自定义线程池
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
        //自定义线程池：因为使用工具类创建得线程池，要么是阻塞队列，要么是最大线程数默认是INTEGER.MAX_VALUE(21亿)造成OOM！
        //获取当前cpu核数
        int cpuCoreNum = Runtime.getRuntime().availableProcessors();
        System.out.println("cpuCoreNum:"+cpuCoreNum);
        return new ThreadPoolExecutor(
                cpuCoreNum,
                cpuCoreNum * 2,
                3,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100),//阻塞队列
                Executors.defaultThreadFactory(),//线程工厂
                new ThreadPoolExecutor.AbortPolicy()
        );
    }
}
